<?php
/**
 * 功能: 9.9包邮
 * User: WD
 * Date: 2018/10/16 0016
 * Time: 9:34
 */

namespace app\admin\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
import('taobao/TopSdk',EXTEND_PATH);
class Free extends Command{

    protected function configure()
    {
        $this->setName('free')->setDescription('9.9包邮');
    }

    protected function execute(Input $input, Output $output){
        $output->writeln("9.9包邮:");
        /*用不超时*/
        ini_set('max_execution_time', 0);
        $this->common_collect();

    }
    public function common_collect(){
        $fileName = __DIR__.'/free_lock.txt';
        $fp = fopen($fileName, "r");
        if(flock($fp,LOCK_EX | LOCK_NB)) {
            $block = '9.9包邮';

            $collector = Db::name('collector')->where('block',$block)->select();
            foreach($collector as $key=>$value){
                $lastTime  = $value['use_time'];//最近一次采集时间

                $last_page  = $value['last_page'];//最后一次采集页数；
                $last_size  = $value['last_size'];//最近一次采集数量
                $page_no    = $value['page_no'];
                $page_size  =  $value['page_size'];

                if(empty($lastTime)){
                    $page            = $page_no;//采集页数
                    $number          = $page_size;//采集数量
                    $last_page  = $page_no;//最后一次采集页数；
                    $last_size  = $page_size;//最近一次采集数量
                }else{
                    if($page_no>$last_page && $page_size>$last_size){
                        $page            = $page_no;
                        $number          = $page_size;
                        $last_page  = $page_no;
                        $last_size  = $page_size;
                    }else{
                        $page            = intval($last_page)+intval($page_no);
                        $number          = intval($page_size);

                        if($last_page>100){
                            $last_page = 100;
                        }else{
                            $last_page  = intval($last_page)+intval($page_no);
                            $last_size  = intval($page_size);
                        }
                    }

                }

                $arr =  [
                    'use_time'=>time(),
                    'last_page'=>$last_page,
                    'last_size'=>$last_size
                ];


                $coll_sort = $value['sort'];
                $sort = '';
                if($coll_sort==1){
                    $sort = 'total_sales_des';
                }elseif($coll_sort==2){
                    $sort = 'tk_rate_des';
                }elseif($coll_sort==3){
                    $sort = 'tk_total_sales_des';
                }elseif($coll_sort==4){
                    $sort = 'price_des';
                }
                $hasCoupon = $value['has_coupon']==0?'false':'true';
                $aid  = get_adzoneid($value['pid']);
                if($value['interface']==1){
                    //安卓
                    $appkey = config('appkeya');
                    $secretKey = config('secreta');
                    if(empty($appkey)||empty($secretKey)){
                        return json(['msg'=>'密匙不存在！','ok'=>false]);
                    }
                }else{
                    //苹果
                    $appkey = config('appkey');
                    $secretKey = config('secret');
                    if(empty($appkey)||empty($secretKey)){
                        return json(['msg'=>'密匙不存在！','ok'=>false]);
                    }
                }

                /*taobao.tbk.dg.material.optional( 通用物料搜索API（导购） )*/
                $c = new \TopClient();
                $c->appkey = $appkey;
                $c->secretKey = $secretKey;
                $req = new \TbkDgMaterialOptionalRequest;
                // $req->setStartDsr("10");
                $req->setPageSize($number);
                $req->setPageNo($page);
                $req->setPlatform("2");//无线端
                $req->setEndTkRate($value['start_tk_rate']);
                $req->setStartTkRate($value['end_tk_rate']);
                /*$req->setEndTkRate("1");
                $req->setStartTkRate("1234");*/
                // $req->setEndPrice("10");//折扣上限
                //  $req->setStartPrice("20");//折扣下限
                $req->setIsOverseas("false");
                $req->setIsTmall("false");
                $req->setSort($sort);
                // $req->setItemloc("杭州");
                // $req->setCat("16,18");
                $req->setQ($value['name'],$block);
                $req->setHasCoupon($hasCoupon);
                // $req->setIp("13.2.33.4");
                $req->setAdzoneId($aid);
                /*$req->setNeedFreeShipment("true");
                $req->setNeedPrepay("true");
                $req->setIncludePayRate30("true");
                $req->setIncludeGoodRate("true");
                $req->setIncludeRfdRate("true");
                $req->setNpxLevel("2");*/
                $resp = $c->execute($req);

                $result =  json_decode(json_encode( $resp),true);
                /* echo "<pre>";
                 print_r($result);die;*/

                if(isset($result['code'])){
                    return  json(['msg'=>'采集器接口错误:'.$result['sub_msg'],'ok'=>false]);
                }
                $goods  = $result['result_list']['map_data'];
                if(!isset($result['result_list'])){
                    return  json(['msg'=>'采集器接口错误!']);
                }
                $list = [];
                foreach($goods as $v){
                    if( empty( $v['num_iid'])){
                        $list[0] =  $goods;
                    }else{
                        $list = $goods;
                    }
                }
                $i = 0;
                $data  = $datas =   [];
                foreach($list as $v){

                    $data['gt_id'] = $value['gt_id'];
                    $data['gb_id'] = $value['gb_id'];
                    $data['interface'] = $value['interface'];
                    $data['goods_add_time'] = time();
                    $data['goods_id'] = $v['num_iid'];//商品ID
                    $data['goods_title'] = $v['title'];//标题
                    $data['goods_big_img'] = $v['pict_url'];//大图地址
                    $data['goods_small_img'] = isset($v['small_images'])?json_encode($v['small_images']):'';
                    $data['goods_detail_url'] = $v['item_url']?$v['item_url']:$v['url'];//商品详情地址
                    $data['goods_volume'] = $v['volume'];//月销量
                    $data['goods_seller_id'] = $v['seller_id'];//供应商ID，卖方id
                    $data['goods_nick'] = isset($v['nick'])?$v['nick']:'';//掌柜旺旺名
                    $data['goods_price'] = isset($v['reserve_price'])?$v['reserve_price']:$v['zk_final_price'];//商品价格
                    $data['goods_z_price'] = $v['zk_final_price'];//折后价


                    $data['goods_price'] = isset($v['reserve_price'])?$v['reserve_price']:$v['zk_final_price'];//商品价格
                    $data['goods_z_price'] = $v['zk_final_price'];//折后价
                    $data['goods_shop_title'] = $v['shop_title'];//店铺名称

                    /*$data['goods_yj_rate'] = $v['commission_rate'];//佣金比例
                    $data['goods_yongjin'] = round($data['goods_price'] * ($v['commission_rate']/10000), 1);//佣金
                    $data['member_yongjin'] = $data['goods_yongjin']/2;//会员佣金*/

                    $time = intval(time()+72*86400);
                    $data['goods_end_time'] = isset($v['coupon_end_time'])?strtotime($v['coupon_end_time']):$time;

                    if(!empty($v['coupon_info'])){
                        $data['state'] = 1;
                        $data['goods_q_price'] = $data['goods_price'] - get_word($v['coupon_info'], '减', '元');//券后价格
                        $data['coupon_id']   = isset($v['coupon_id'])?$v['coupon_id']:'';
                        $data['coupon_info'] = $v['coupon_info'];
                        $data['coupon_end_time'] = isset($v['coupon_end_time'])?$v['coupon_end_time']:0;//优惠券结束时间
                        $data['coupon_start_time'] = isset($v['coupon_start_time'])?$v['coupon_start_time']:0;//优惠券开始时间
                        $data['coupon_total_count'] = isset($v['coupon_total_count'])?$v['coupon_total_count']:0;//优惠券结总数
                        $data['coupon_remain_count'] = isset($v['coupon_remain_count'])?$v['coupon_remain_count']:0;//优惠券剩余量
                        $data['coupon_amount'] = get_word($v['coupon_info'], '减', '元');
                        $data['coupon_click_url'] = isset($v['coupon_share_url'])?$v['coupon_share_url']:(isset($v['coupon_click_url'])?$v['coupon_click_url']:'');//优惠券链接地址//推广链接
                        $data['coupon_total_count'] = $v['coupon_total_count'];//优惠券数量
                        $data['coupon_remain_count'] = $v['coupon_remain_count'];//优惠券 剩余量

                    }else{
                        $data['goods_q_price'] = $v['reserve_price'];
                        $data['state'] = 0;
                        $data['coupon_id']   = '';
                        $data['coupon_info'] = '';
                        $data['coupon_end_time'] = 0;//优惠券结束时间
                        $data['coupon_start_time'] = 0;//优惠券开始时间
                        $data['coupon_total_count'] = 0;//优惠券结总数
                        $data['coupon_remain_count'] = 0;//优惠券剩余量
                        $data['coupon_amount'] = 0;
                        $data['coupon_click_url'] = '';//优惠券链接地址//推广链接
                        $data['coupon_total_count'] = 0;//优惠券数量
                        $data['coupon_remain_count'] = 0;//优惠券 剩余量
                    }

                    $data['goods_yj_rate'] = $v['commission_rate'];//佣金比例
                    if($data['goods_price']!=0 && $data['goods_z_price']!=0 && $data['goods_q_price']!=0){
                        $min = min($data['goods_price'],$data['goods_z_price'],$data['goods_q_price']);
                        $data['goods_yongjin'] = round($min* ($v['commission_rate']/10000), 1);//佣金
                        $data['member_yongjin'] = $data['goods_yongjin']/2;//会员佣金
                    }

                    $data['goods_city'] = isset($v['provcity'])?$v['provcity']:'';//商品所在城市
                    $data['goods_user_type'] = $v['user_type'];//卖家类型,1表示天猫

                    $check_repeat = Db::name('goods')->where('goods_id',$data['goods_id'])->find();//检查重复
                    /* print_r($check_repeat);
die;*/
                    if(empty($check_repeat)){
                        if($data['coupon_info']){
                            if($data['goods_price']<=9.9||$data['goods_q_price']<=9.9){
                                $datas[] = $data;
                            }
                        }else{
                            if($data['goods_z_price']<=9.9){
                                $datas[] = $data;
                            }
                        }


                    }else{
                        Db::startTrans();
                        try{
                            if($data['coupon_info']){
                                if($data['goods_price']<=9.9||$data['goods_q_price']<=9.9){
                                    $success = Db::name('goods')->where('goods_id','=',$data['goods_id'])->update($data);
                                    Db::name('Collector')->where('id','=',$value['id'])->update($arr);
                                }
                            }else{
                                if($data['goods_z_price']<=9.9){
                                    $success = Db::name('goods')->where('goods_id','=',$data['goods_id'])->update($data);
                                    Db::name('Collector')->where('id','=',$value['id'])->update($arr);
                                }
                            }

                            // 提交事务
                            Db::commit();
                            //   return json(['msg'=>'采集成功！','ok'=>true]);
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                            //  return json(['msg'=>$e->getMessage(),'ok'=>false]);
                        }

                    }
                    $i++;
                }
                /* echo "<pre>";
                  print_r($data);
                  print_r($datas);
          die;*/

                $res1 = second_array_unique_bykey($datas, 'goods_id');
                if(!empty($res1)){
                    Db::startTrans();
                    try{
                        foreach($res1 as $k=>$v){
                            $check_repeat = Db::name('goods')->where('goods_id',$v['goods_id'])->find();//检查重复
                            if(empty($check_repeat)){
                                if($v['coupon_info']){
                                    if($v['goods_price']<=9.9||$v['goods_q_price']<=9.9){
                                        $success = Db::name('goods')->insertAll($datas);
                                        Db::name('Collector')->where('id','=',$value['id'])->update($arr);
                                    }
                                }else{
                                    if($v['goods_z_price']<=9.9){
                                        $success = Db::name('goods')->insertAll($datas);
                                        Db::name('Collector')->where('id','=',$value['id'])->update($arr);
                                    }
                                }
                            }


                        }

                        // 提交事务
                        Db::commit();

                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                    }

                }
            }
        }
        fclose($fp);


    }

}